const { query } = require('../../../lib/db');
const { authenticateToken } = require('../../../lib/auth');
const { validate } = require('../../../lib/validation');
const Joi = require('joi');

// 产品模块创建验证Schema
const createProductModuleSchema = Joi.object({
  product_id: Joi.number().integer().positive().required(),
  name: Joi.string().max(100).required(),
  code: Joi.string().max(50).required(),
  module_type: Joi.string().valid('core', 'plugin', 'addon', 'integration').default('core'),
  responsible_team: Joi.string().max(100),
  technical_lead_id: Joi.number().integer().positive(),
  description: Joi.string(),
  api_endpoint: Joi.string().max(500).uri(),
  database_schema: Joi.string().max(100),
  dependencies: Joi.string(),
  complexity_level: Joi.string().valid('simple', 'medium', 'complex', 'critical').default('medium'),
  maintenance_frequency: Joi.string().valid('daily', 'weekly', 'monthly', 'quarterly', 'yearly').default('monthly')
});

async function handler(req, res) {
  try {
    switch (req.method) {
      case 'GET':
        return await getProductModules(req, res);
      case 'POST':
        return await createProductModule(req, res);
      default:
        return res.status(405).json({
          success: false,
          message: '方法不允许'
        });
    }
  } catch (error) {
    console.error('产品模块API错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

async function getProductModules(req, res) {
  try {
    // Simplified query for debugging
    const modules = await query('SELECT * FROM product_modules LIMIT 50');
    
    res.status(200).json({
      success: true,
      data: modules
    });
  } catch (error) {
    console.error('Product modules query error:', error);
    res.status(500).json({
      success: false,
      message: 'Database query failed',
      error: error.message
    });
  }
}

async function createProductModule(req, res) {
  const validation = validate(createProductModuleSchema, req.body);
  if (!validation.isValid) {
    return res.status(400).json({
      success: false,
      message: '请求数据验证失败',
      errors: validation.errors
    });
  }

  const {
    product_id,
    name,
    code,
    module_type,
    responsible_team,
    technical_lead_id,
    description,
    api_endpoint,
    database_schema,
    dependencies,
    complexity_level,
    maintenance_frequency
  } = validation.data;

  // 验证产品存在
  const product = await query('SELECT id FROM products WHERE id = ? AND status = 1', [product_id]);
  if (!product.length) {
    return res.status(400).json({
      success: false,
      message: '指定的产品不存在或已禁用'
    });
  }

  const result = await query(`
    INSERT INTO product_modules (
      product_id, name, code, module_type, responsible_team, 
      technical_lead_id, description, api_endpoint, database_schema,
      dependencies, complexity_level, maintenance_frequency
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `, [
    product_id, name, code, module_type, responsible_team,
    technical_lead_id, description, api_endpoint, database_schema,
    dependencies, complexity_level, maintenance_frequency
  ]);

  const newModule = await query(`
    SELECT pm.*, 
           p.name as product_name,
           tech_user.name as technical_lead_name
    FROM product_modules pm
    LEFT JOIN products p ON pm.product_id = p.id
    LEFT JOIN users tech_user ON pm.technical_lead_id = tech_user.id
    WHERE pm.id = ?
  `, [result.insertId]);

  res.status(201).json({
    success: true,
    message: '产品模块创建成功',
    data: newModule[0]
  });
}

export default authenticateToken(handler);